package com.atilim.cargo.business;

import java.util.Collection;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.atilim.cargo.model.BaseModel;
import com.atilim.cargo.model.User;



//Bütün iş sınıflarının babası
public abstract class BaseBean {

	@PersistenceContext (unitName="Servis")
	EntityManager em; //jpa standartı bir arayüz içinde kod yok .
	
	public User findById(long id) {
		return this.em.find(User.class, id);
	}

	public User find(String username, String password) {
		String sql = "from User where username = :username and password = :password";
		Query q = this.em.createQuery(sql);
		q.setParameter("username", username);
		q.setParameter("password", password);
		try {
			return (User) q.getSingleResult();			
		} catch (NoResultException e) {
			return null;
		}
	}
	
	public <T extends BaseModel> List<T> executeQuery(Class<T> type, String sql) {
		return  (List<T>) this.em.createQuery(sql, type).getResultList();
	}

	public <T extends BaseModel> List<T> find(Class<T> type, Map<String, Object> params) {
		String sql = "from " + type.getSimpleName() + " where ";
		
		for (String key : params.keySet()) {
			sql += " " + key + " like :" + key + " and"; 
		}
		
		sql += " 1 = 1 ";
		
		Query query = this.em.createQuery(sql, type);
		for (String key : params.keySet()) {
			query.setParameter(key, params.get(key) + "%"); 
		}
		
		return query.getResultList();
	}
	
	static <T> void fromArrayToCollection(T[] a, Collection<T> c) {
	    for (T o : a) {
	        c.add(o); // Correct
	    }
	}

	public void insertObject(BaseModel model)  {
		this.em.persist(model);
		
	}

	public void updateObject(BaseModel model)  {
		this.em.merge(model);
	}

	public void deleteObject(BaseModel model)  {
		this.em.remove(model);
	}


	public <T extends BaseModel> T getObject(Class<T> type, long id) {
		return this.em.find(type, id);
	}
	
	

	
}
